import React, {Component} from 'react';

let UsernameContext = React.createContext()

class A extends Component {
    state = {
        username: 'tom'
    }

    render() {
        let {username} = this.state;
        return (
            <div>
                <h4>我是A组件</h4>
                <h4>我的用户名是：{username}</h4>
                <UsernameContext.Provider value={username}>
                    <B/>
                </UsernameContext.Provider>
            </div>
        );
    }
}

export default A;


class B extends Component {
    render() {
        return (
            <div>
                <h4>我是B组件</h4>
                <h4>我从A组件接收的用户名是：？？？</h4>
                <C/>
            </div>
        );
    }
}

/*class C extends Component {
    //声明接收context
    static contextType = UsernameContext

    render() {
        return (
            <div>
                <h4>我是C组件</h4>
                <h4>我从A组件接收的用户名是：{this.context}</h4>
            </div>
        );
    }
}*/

function C() {
    return (
        <div>
            <h4>我从A组件接收的用户名是:
                <UsernameContext.Consumer>
                    {value => {return `${value}`}}
                </UsernameContext.Consumer>
                <h4>我是C组件</h4>
            </h4>
        </div>
    )
}
